package com.cyl.XmlDemo.service;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import com.cyl.XmlDemo.entity.Room;
import com.cyl.XmlDemo.entity.Shout;

@Service
public class MessageService {
	
	private static final Logger logger = LoggerFactory.getLogger(MessageService.class);
	
	private static final String COMMON_CHANNEL = "/topic/common/message";
	private static final String PRIVATE_CHANNEL = "/topic/private/message";
	
	@Autowired
	private SimpMessagingTemplate messaging;
	
	@Autowired
	private Room room;
	
	/**
	 * 对公共频道进行广播
	 * @param msg 需要广播的信息
	 */
	public void boardcast(String payload){
		messaging.convertAndSend(COMMON_CHANNEL, payload);
	}
	
	/**
	 * 对指定频道进行广播
	 * @param destination 目标频道
	 * @param payload 需要广播的信息
	 */
	public void boardcastByDestination(String destination,String payload){
		messaging.convertAndSend(destination, payload);
	}
	
	/**
	 * 发送信息给指定用户
	 * @param user 目标用户
	 * @param payload 信息
	 */
	public void sendMsg(String user,Shout shout){
//		Shout shout = new Shout();
//		shout.setCmd(cmd);
		messaging.convertAndSendToUser(user, PRIVATE_CHANNEL, shout);
	}
	
	public void sendCMD(String user,Shout shout){
		/*Shout shout = new Shout();
		shout.setCmd(cmd);*/
		String[] callee = new String[room.size()-1];
		Iterator<String> iterator = room.iterator();
		int i = 0;
		while(iterator.hasNext()){
			String uuid = iterator.next();
			//不能把元数据发回给自己
			if(!uuid.equals(user)){
				callee[i] = uuid;
				i++;
			}
		}
		shout.setData(callee);
		messaging.convertAndSendToUser(user, PRIVATE_CHANNEL, shout);
	}
	
	/**
	 * 传送会话元数据
	 * @param uniqueName 发送者
	 * @param metaData 会话元数据
	 */
	public void transferMetaData(Shout shout){
		messaging.convertAndSendToUser(shout.getCallee(), PRIVATE_CHANNEL, shout);
	}
	
}
